package com.wgj.android.ui.activity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.jiaai.xui.XUI;

import com.jiaai.xui.cache.XCache;

import com.jiaai.xui.utils.XBitmapUtils;

import com.jiaai.xui.utils.XDensityUtils;
import com.jiaai.xui.utils.XEmptyUtils;
import com.jiaai.xui.utils.share.ShareUtils;
import com.jiaai.xui.utils.share.entity.Share;
import com.jiaai.xui.utils.statusbar.XStatusBar;
import com.jiaai.xui.view.widget.XLoadingDialog;
import com.jiaai.xui.view.widget.XToast;
import com.jiaai.xui.view.widget.XTopbarView;
import com.wgj.android.R;
import com.wgj.android.accesslibility.service.WXShareAccesslibilityService;
import com.wgj.android.dialog.ManyDiadlog;
import com.wgj.android.dialog.ShareDiadlog;
import com.wgj.android.entity.Member;
import com.wgj.android.entity.SystemConfg;
import com.wgj.android.http.WGJAPI;
import com.wgj.android.utils.CacheUtils;
import com.wgj.android.utils.QRCodeUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Field;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/11/4.
 */

public class MyQrCodeActivity extends AppCompatActivity implements  XTopbarView.OnTopBarClickListener ,ShareDiadlog.OnShareListener,ManyDiadlog.ManyDiadlogListener{
    @BindView(R.id.topbarView)
    XTopbarView topbarView;

    @BindView(R.id.codeImg)
    ImageView codeImg;

    private int shareType;

    private Member member;

    private  SystemConfg confg;
    private   Share share;

    private  ShareDiadlog shareDiadlog;
    private  ManyDiadlog manyDiadlog;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)  {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.my_qr_code_activtiy);
        shareDiadlog=new ShareDiadlog().setOnShareListener(this);
        manyDiadlog=new ManyDiadlog().setDiadlogListener(this);
        shareType=getIntent().getIntExtra("type",0);
        member= CacheUtils.getMember();
        confg=CacheUtils.getSystemConfig();
        XStatusBar.setColor(this, Color.parseColor("#333333"));
        ButterKnife.bind(this);
        topbarView.setTopBarClickListener(this);
        Bitmap bitmap=XCache.get(this).getAsBitmap(member.getM_id()+"share_qr_code");
        XLoadingDialog.with(this).setMessage("正在生成二维码").show();

        share=new Share();
        share.setThumBitmap(XBitmapUtils.getBitmapFromDrawable(XUI.getDrawable(R.mipmap.logo)));
        share.setTitle(confg.getSharetitle());
        share.setWebUrl(member.getShareUrl());
        share.setDescription(confg.getSharecontent());
        if(bitmap!=null){
             codeImg.setImageBitmap(bitmap);
            XLoadingDialog.with(MyQrCodeActivity.this).dismiss();
        }else {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    final String filePath =getFileRoot(MyQrCodeActivity.this)+ File.separator+member.getM_id()+"_share_qr_code.jpg";
                    boolean success= QRCodeUtil.createQRImage(
                                member.getShareUrl(),
                                800,
                                800,
                                 XBitmapUtils.getBitmapFromDrawable(XUI.getDrawable(R.mipmap.logo)),
                                filePath);
                    if(success){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Bitmap b=XBitmapUtils.getBitmapFromFile(filePath, XDensityUtils.dp2px(65),XDensityUtils.dp2px(65));
                                XCache.get(MyQrCodeActivity.this).put(member.getM_id()+"share_qr_code",b);
                                codeImg.setImageBitmap(b);
                                XLoadingDialog.with(MyQrCodeActivity.this).dismiss();
                            }
                        });
                    }
                }
            }).start();
        }

    }


    //文件存储根目录
    private String getFileRoot(Context context) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File external = context.getExternalFilesDir(null);
            if (external != null) {
                return external.getAbsolutePath();
            }
        }

        return context.getFilesDir().getAbsolutePath();
    }




    @Override
    public void onBackClick() {
         finish();
    }
    @OnClick(R.id.qrBgg) void  onClick(View view){
        if(shareType==0){
            shareDiadlog.show(getSupportFragmentManager(),"shareDialog");
        }else {
            manyDiadlog.show(getSupportFragmentManager(),"manyDiadlog");
        }

    }

    @Override
    public void onRightButClick() {
        if(shareType==0){
            shareDiadlog.show(getSupportFragmentManager(),"shareDialog");
        }else {
            manyDiadlog.show(getSupportFragmentManager(),"manyDiadlog");
        }
 }

    @Override
    public void onItemClick(int index) {
        switch (index){
            case 0:
                String savePath=getSDCardPath()+File.separator+"旺旺通"+File.separator+"ScreenImage";
                File path=new File(savePath);
                if(!path.exists()){
                    path.mkdirs();
                }
                String filePath= savePath+File.separator+member.getM_id()+"_share1.png";
                File file=new File(filePath);
                GetandSaveCurrentImage(file);
                break;
            case 1:

                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                cm.setPrimaryClip(ClipData.newPlainText(null, member.getShareUrl()));
                XToast.success("分享接连已复制到粘贴板,可以发送给朋友们了.");
                break;
            case 2:
                WXShareAccesslibilityService.start();
                ComponentName comp = new ComponentName("com.tencent.mm","com.tencent.mm.ui.LauncherUI");
                Intent it = new Intent();
                it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//需要加这个不然会报错
                it.setComponent(comp);
                startActivity(it);
                break;

        }

    }



    @Override
    public void onShareWeiXin() {
        if(XEmptyUtils.isSpace(confg.getWXAppId())){
            XToast.error("暂未开放");
        }else {
            ShareUtils.shareWeiXin(getApplication(),share,confg.getWXAppId(),false);
            shareDiadlog.dismiss();
        }
    }

    @Override
    public void onShareFriends() {
        if(XEmptyUtils.isSpace(confg.getWXAppId())){
            XToast.error("暂未开放");
        }else {
            ShareUtils.shareWeiXin(getApplication(),share,confg.getWXAppId(),true);
            shareDiadlog.dismiss();
        }
    }

    @Override
    public void onShareSpaceBut() {
        XToast.error("暂未开放");
    }
    @Override
    public void onShareQQ() {
        XToast.error("暂未开放");
    }

    @Override
    public void onlinkButBut() {
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        cm.setPrimaryClip(ClipData.newPlainText(null, member.getShareUrl()));
        XToast.success("分享接连已复制到粘贴板,可以发送给朋友们了.");
    }


    /**
     * 获取和保存当前屏幕的截图
     */
    private void GetandSaveCurrentImage(File file)
    {
        //1.构建Bitmap
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        int w = display.getWidth();
        int h = display.getHeight();

        Bitmap Bmp = Bitmap.createBitmap( w, h, Bitmap.Config.ARGB_8888 );
        //2.获取屏幕
        View decorview = this.getWindow().getDecorView();
        decorview.setDrawingCacheEnabled(true);
        Bmp = decorview.getDrawingCache();


        //3.保存Bitmap
        try {

            file.createNewFile();
            FileOutputStream fos = null;
            fos = new FileOutputStream(file);
            if (null != fos) {
                Bmp.compress(Bitmap.CompressFormat.PNG, 90, fos);
                fos.flush();
                fos.close();
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri uri = Uri.fromFile(file);
                intent.setData(uri);
                getApplication().sendBroadcast(intent);
                XToast.success("截屏文件已保存至"+file.getPath(),3000);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取SDCard的目录路径功能
     * @return
     */
    private String getSDCardPath(){
        File sdcardDir = null;
        //判断SDCard是否存在
        boolean sdcardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
        if(sdcardExist){
            sdcardDir = Environment.getExternalStorageDirectory();
        }
        return sdcardDir.toString();
    }
}
